package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service(interfaceClass = MemberService.class)
@Transactional
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberDao memberDao;

    @Autowired
    private OrderDao orderDao;

    @Override
    public Member findMemberBytelephone(String telephone) {

        return memberDao.findByTelephone(telephone);
    }

    @Override
    public void add(Member member) {
        //来自不同渠道的的登录，有密码的注册登录，需要对密码进行加密
        String password = member.getPassword();
        if(password!=null){
            password = MD5Utils.md5(password);
            member.setPassword(password);
        }
        memberDao.add(member);
    }

    @Override
    public List<Integer> findMemberByDateList(ArrayList<String> monthList) {
        List<Integer> members = new ArrayList<>();
        for (String month : monthList) {
            month=month+".31";
            Integer countEverMonth = memberDao.findMemberByDateList(month);
            members.add(countEverMonth);
        }
        return members;
    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {

         PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());

        Page<Member> page=memberDao.findMemberByCondition(queryPageBean.getQueryString());

        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public Member getById(Integer id) {
        return memberDao.findById(id);
    }

    @Override
    public void update(Member member) {
        memberDao.edit(member);
    }

    @Override
    public void deleteById(Integer id) {
        orderDao.deleteMember2OrderByMemberId(id);
        memberDao.deleteById(id);
    }
}
